import tool.TreeNode;
import tool.TreeNodePrint;
import tool.input;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @Description: 对称二叉树
 * 给你一个二叉树的根节点 root ， 检查它是否轴对称
 * @Date:Create in 20:49  2022/7/21
 */
public class isSymmetric0101 {

    public static void main(String[] args) {
        String s = "[1,2,2,3,4,4,3]";
        TreeNode root = input.getTree(s);
        TreeNodePrint.printTree(root);
        boolean bool = isSymmetric2(root);
        System.out.println(bool);
    }


    //递归方法
    public static boolean isSymmetric1(TreeNode root) {
        return compare(root.left, root.right);
    }

    private static boolean compare(TreeNode left, TreeNode right) {
        if (left == null && right != null) {
            return false;
        }
        if (left != null && right == null) {
            return false;
        }
        if (left == null && right == null) {
            return true;
        }
        if (left.val != right.val) {
            return false;
        }

        boolean compareOut = compare(left.left, right.right);
        boolean compareIn = compare(left.right, right.left);
        return compareOut && compareIn;
    }


    /**
     * 迭代法
     * 使用普通队列
     */
    public static boolean isSymmetric2(TreeNode root) {
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root.left);
        deque.offer(root.right);
        while (!deque.isEmpty()) {
            TreeNode leftNode = deque.poll();
            TreeNode rightNode = deque.poll();
            if (leftNode == null && rightNode == null) {
                continue;
            }
            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val){
                return false;
            }
            deque.offer(leftNode.left);
            deque.offer(rightNode.right);
            deque.offer(leftNode.right);
            deque.offer(rightNode.left);
        }
        return true;
    }
}
